package settings;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.imstlife.vending.R;
import com.imstlife.vending.activity.BaseActivity;
import com.imstlife.vending.adapter.SettingsItemAdapter;
import com.imstlife.vending.utils.DeviceUtil;
import com.imstlife.vending.utils.T;

import java.lang.ref.WeakReference;

public class SettingsActivity extends BaseActivity {



    private ListView itemListView;
    private SettingsItemAdapter adapter;

    private ImageView backImageView;

    /**
     * 日期与时间
     */
    private DateAndTimeFragment dateAndTimeFragment;

    /**
     * WiFi
     */
    private WiFiFragment wiFiFragment;

    /**
     * 更多
     */
    private MoreSettingsFragment moreSettingsFragment;

    /**
     * 关于
     */
    private AboutAppFragment aboutAppFragment;

    //货道检测
    private CheckOutTradeFragment checkOutTradeFragment;

    //一键货道检测
    private CheckOutTradeAllFragment checkOutTradeAllFragment;

    private ManageFragment manageFragment;

    /**
     * 应用设置
     */
    private Fragment appSetFragment;

    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager fragmentManager;

    /**
     * 显示WiFi状态
     */
    private ImageView wifiStateIv;
    /**
     * 显是否检测WiFi状态
     */
    private boolean isWiFiDetection = false;

    private TextView tvDeviceId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏ActionBar
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_settings_twopane);

        Log.e("SettingsActivity", "onCreate");

        initLayout();

        itemListView = (ListView) findViewById(R.id.ac_settings_item_list);

        adapter = new SettingsItemAdapter(this);
        itemListView.setAdapter(adapter);
        itemListView.setOnItemClickListener(new ItemClickListener());

        fragmentManager = this.getSupportFragmentManager();

        // 第一次启动时选中第0个tab
        setTabSelection(0);

        // 启动WiFi状态监测
        startWifiDetection();

        T.showLong(this,"model:"+getIntent().getStringExtra("deviceModel"));
    }

    private void initLayout() {
        backImageView = (ImageView) findViewById(R.id.ac_settings_back);
        backImageView.setOnClickListener(new ButtonClickListener());

        wifiStateIv = (ImageView) findViewById(R.id.ac_settings_iv_wifi);

        tvDeviceId = (TextView) findViewById(R.id.tv_ac_setting_deviceId);
        String deviceId = DeviceUtil.getDeviceId(SettingsActivity.this);
        if (deviceId != null) {
            tvDeviceId.setText("设备号：" + deviceId);
        }
    }

    private class ButtonClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.ac_settings_back:
                    finish();

                    break;
                default:
                    break;
            }
        }

    }

    private class ItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            setTabSelection(position);

            adapter.setSelectItem(position);
            // 通知adapter刷新数据
            adapter.notifyDataSetInvalidated();
        }
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
     */
    private void setTabSelection(int index) {
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                if (wiFiFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    wiFiFragment = new WiFiFragment();
                    transaction.add(R.id.ac_settings_item_detail_container,
                            wiFiFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(wiFiFragment);
                }
                T.showLong(SettingsActivity.this,"3G网络，设置wifi无效");
                break;
            case 1:
                if (dateAndTimeFragment == null) {
                    // 如果ContactsFragment为空，则创建一个并添加到界面上
                    dateAndTimeFragment = new DateAndTimeFragment();
                    transaction.add(R.id.ac_settings_item_detail_container,
                            dateAndTimeFragment);
                } else {
                    // 如果ContactsFragment不为空，则直接将它显示出来
                    transaction.show(dateAndTimeFragment);
                }
                break;
            case 2:
                if (moreSettingsFragment == null) {
                    // 如果NewsFragment为空，则创建一个并添加到界面上
                    moreSettingsFragment = new MoreSettingsFragment();
                    transaction.add(R.id.ac_settings_item_detail_container,
                            moreSettingsFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(moreSettingsFragment);
                }
                break;

            case 3:
                if (manageFragment == null) {
                    // 如果NewsFragment为空，则创建一个并添加到界面上
                    manageFragment = new ManageFragment();
                    transaction.add(R.id.ac_settings_item_detail_container,
                            manageFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(manageFragment);
                }
                break;

            case 4:
                if (checkOutTradeFragment==null){
                    checkOutTradeFragment = new CheckOutTradeFragment();
                    transaction.add(R.id.ac_settings_item_detail_container,checkOutTradeFragment);
                }else{
                    transaction.show(checkOutTradeFragment);
                }
                break;
            case 5:
                if (checkOutTradeAllFragment==null){
                    checkOutTradeAllFragment = new CheckOutTradeAllFragment();
                    transaction.add(R.id.ac_settings_item_detail_container,checkOutTradeAllFragment);
                }else{
                    transaction.show(checkOutTradeAllFragment);
                }
                break;
            case 6:
                if (aboutAppFragment == null) {
                    // 如果NewsFragment为空，则创建一个并添加到界面上
                    aboutAppFragment = new AboutAppFragment();
                    transaction.add(R.id.ac_settings_item_detail_container,
                            aboutAppFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(aboutAppFragment);
                }
                break;



        }

        transaction.commit();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (wiFiFragment != null) {
            transaction.hide(wiFiFragment);
        }
        if (dateAndTimeFragment != null) {
            transaction.hide(dateAndTimeFragment);
        }
        if (moreSettingsFragment != null) {
            transaction.hide(moreSettingsFragment);
        }
        if (aboutAppFragment != null) {
            transaction.hide(aboutAppFragment);
        }
        if (appSetFragment != null) {
            transaction.hide(appSetFragment);
        }
        if (checkOutTradeFragment!=null){
            transaction.hide(checkOutTradeFragment);
        }
        if (checkOutTradeAllFragment!=null){
            transaction.hide(checkOutTradeAllFragment);
        }
        if(manageFragment!=null){
            transaction.hide(manageFragment);
        }
    }

    @Override
    protected void onDestroy() {
        Log.e("SettingsActivity", "onDestroy");

        super.onDestroy();
    }

    private Handler mHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private final WeakReference<SettingsActivity> mActivity;

        public MyHandler(SettingsActivity activity) {
            mActivity = new WeakReference<SettingsActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SettingsActivity theActivity = mActivity.get();
            if (theActivity == null) {
                return;
            }

            switch (msg.what) {
                // 接收到321倒计时消息

                case 0x901:
                    theActivity.obtainWiFiInfo();
                    break;

                default:
                    break;
            }

            super.handleMessage(msg);
        }

    }

    /**
     * 扫描WiFi信号
     */
    public void startWifiDetection() {
        isWiFiDetection = true;
        new wifiDetection().start();
    }

    public void stopWifiDetection() {
        isWiFiDetection = false;
    }

    class wifiDetection extends Thread {
        @Override
        public void run() {
            super.run();
            while (isWiFiDetection) {

                Message msg = new Message();
                msg.what = 0x901;
                mHandler.sendMessage(msg);

                try {
                    sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void obtainWiFiInfo() {

        // WiFi的连接速度及信号强度：
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        // System.out.println("info.getBSSID()"+ info.getBSSID());
        // System.out.println("info.getSSID()"+ info.getSSID());
        // System.out.println("info.getSSID()" + info.getIpAddress());
        if (!"0".equals(info.getIpAddress())) {
            wifiStateIv.setVisibility(View.VISIBLE);
            // 链接信号强度
            int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5);
            // System.out.println("信号强度" + strength);
            refreshWifi(strength, wifiStateIv);
            // 链接速度
            int speed = info.getLinkSpeed();
            // 链接速度单位
            String units = WifiInfo.LINK_SPEED_UNITS;
            // WiFi源名称
            String ssid = info.getSSID();
        } else {
            wifiStateIv.setVisibility(View.GONE);
        }

    }

    public void refreshWifi(int rssi, ImageView wifiStateImage) {

        if (rssi == 0) {
            wifiStateImage.setImageResource(R.mipmap.wifi0);
            // wifiStateImage.setVisibility(View.GONE);
        } else if (rssi == 1) {
            wifiStateImage.setImageResource(R.mipmap.wifi1);
        } else if (rssi == 2) {
            wifiStateImage.setImageResource(R.mipmap.wifi2);
        } else if (rssi == 3) {
            wifiStateImage.setImageResource(R.mipmap.wifi3);
        } else if (rssi == 4) {
            wifiStateImage.setImageResource(R.mipmap.wifi4);
        } else {
            wifiStateImage.setVisibility(View.GONE);
        }
    }


}
